/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Utils;

import java.io.File; // File
import java.io.IOException; // IOException
import java.awt.image.BufferedImage; // BufferedImage
import javax.imageio.ImageIO; // ImageIO

/**
 *
 * @author Agapito
 */
public class ImageBW {

    public int[][] pix;
    public int lx;
    public int ly;

    /**
     * Formula para calcular el color gris
     * @param r
     * @param g
     * @param b
     * @return
     */
    public static int calcGris(int r, int g, int b) {
        return (int) (r * 0.299 + g * 0.511 + b * 0.114);
    }

    /**
     * Constructor
     * @param lx
     * @param ly
     */
    public ImageBW(int lx, int ly) {
        this.pix = new int[lx][ly];
        this.lx = lx;
        this.ly = ly;
    }

    /**
     * Constructor
     * @param fileName
     * @throws java.io.IOException
     */
    public ImageBW(String fileName) throws IOException {
        File infile = new File(fileName);
        BufferedImage im = ImageIO.read(infile);
        int r, g, b, rgb;

        this.lx = im.getWidth();
        this.ly = im.getHeight();
        this.pix = new int[this.lx][this.ly];
        for (int i = 0; i < this.lx; i++) {
            for (int j = 0; j < this.ly; j++) {
                rgb = im.getRGB(i, j); // color RGB mezclado: R:bits 16-23, B:bits 8-15, B:bits 0-7

                // Ahora, separar las componentes
                r = (rgb >> 16) & 255;// bits 16-23. El &255 deja los ultimos 8 bits.
                g = (rgb >> 8) & 255; // bits 8-15
                b = rgb & 255; // bits 0-7

                this.pix[i][j] = calcGris(r, g, b); // trasformar a tonos de gris
            }
        }
    }

    /**
     * Save an image as it is in BW
     * @param fileName
     * @param type
     * @throws java.io.IOException
     */
    public void save(String fileName, String type) throws IOException {
        
        // nueva imagen RGB
        BufferedImage im = new BufferedImage(this.lx, this.ly, BufferedImage.TYPE_INT_RGB);

        int i, j;
        int r, g, b;
        int rgb;
        for (i = 0; i < this.lx; i++) {
            for (j = 0; j < this.ly; j++) {
                r = this.pix[i][j]; // color rojo
                g = this.pix[i][j]; // color verde
                b = this.pix[i][j]; // color azul

                rgb = (r << 16) + (g << 8) + b; // Volver a mezclar las componentes
                im.setRGB(i, j, rgb);
            }
        }
        File outfile = new File(fileName);
        ImageIO.write(im, type, outfile);
    }
}
